package cn.stronglink.esm27.collection.iot.devices.camera.util;

import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Base64EncryptUtil {

	private static final byte[] DESkey = "Rx2012#@".getBytes();// 设置密钥
	private static final byte[] DESIV = "Rx2012#@".getBytes();// 设置向量

	static AlgorithmParameterSpec iv = null;// 加密算法的参数接口，IvParameterSpec是它的一个实现
	private static Key key = null;

	public Base64EncryptUtil() throws Exception {
		
	}

	public static String encrypt(String data) throws Exception {
		DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数
		iv = new IvParameterSpec(DESIV);// 设置向量
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
		key = keyFactory.generateSecret(keySpec);// 得到密钥对象
		Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
		enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
		byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
		Base64.Encoder encoder = Base64.getEncoder();
		return encoder.encodeToString(pasByte);
	}

	public static String decrypt(String data) throws Exception {
		DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数
		iv = new IvParameterSpec(DESIV);// 设置向量
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
		key = keyFactory.generateSecret(keySpec);// 得到密钥对象
		Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		deCipher.init(Cipher.DECRYPT_MODE, key, iv);
		Base64.Decoder decoder = Base64.getDecoder();
		byte[] pasByte = deCipher.doFinal(decoder.decode(data));
		return new String(pasByte, "UTF-8");
	}

	

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		System.out.println(encrypt("192.168.1.22"));//加密ip
		System.out.println(encrypt("admin"));// 加密用户名
		System.out.println(encrypt("krund0808"));//加密密码
		System.out.println(decrypt("InAmX32MCQ4="));//解密
		// System.out.println(UUID.randomUUID().toString());
	}

}
